package com.luci.sys.service.impl;

import com.baomidou.mybatisplus.extension.api.Assert;
import com.google.common.collect.Maps;
import com.luci.common.exception.ApiCode;
import com.luci.common.supers.SuperServiceImpl;
import com.luci.sys.entity.Role;
import com.luci.sys.entity.UserRole;
import com.luci.sys.mapper.RoleMapper;
import com.luci.sys.service.IRoleService;
import com.luci.sys.service.IUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author yuyanan
 * @since 2019-05-09
 */
@Service
public class RoleServiceImpl extends SuperServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private IUserRoleService iUserRoleService;

    @Override
    public Role getByUserId(String userId) {
        UserRole userRole = iUserRoleService.getByUserId(userId);
        if (userRole == null) {
            return null;
        }
        return this.getById(userRole.getRoleId());
    }

    @Override
    public Map<String, Role> getMapByUserIds(List<String> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return Maps.newHashMap();
        }
        // 查询role集合
        List<UserRole> userRoles = iUserRoleService.getByUserIds(userIds);
        if (userRoles.isEmpty()) {
            return Maps.newHashMap();
        }
        // 获取roleIds
        List<String> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());

        Collection<Role> roles = listByIds(roleIds);
        if (roles.isEmpty()) {
            return Maps.newHashMap();
        }
        Map<String, Role> roleMap = roles.stream().collect(Collectors.toMap(Role::getId, x -> x, (value1, value2) -> value2));
        //用户id ：角色
        Map<String, Role> result = userRoles.stream().collect(Collectors.toMap(UserRole::getUserId, x -> roleMap.get(x.getRoleId()), (value1, value2) -> value2));
        return result;
    }

    @Override
    public List<Role> getByUserIds(List<String> userIds) {
        return null;
    }
}
